package com.sqx.modules.pay.controller.app;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradeWapPayRequest;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sqx.common.utils.DateUtils;
import com.sqx.common.utils.Result;
import com.sqx.modules.app.annotation.Login;
import com.sqx.modules.app.dao.UserMoneyDao;
import com.sqx.modules.app.entity.UserEntity;
import com.sqx.modules.app.entity.UserMoneyDetails;
import com.sqx.modules.app.service.UserMoneyDetailsService;
import com.sqx.modules.app.service.UserService;
import com.sqx.modules.common.entity.CommonInfo;
import com.sqx.modules.common.service.CommonInfoService;
import com.sqx.modules.pay.config.AliPayConstants;
import com.sqx.modules.pay.dao.PayDetailsDao;
import com.sqx.modules.pay.entity.PayDetails;
import com.sqx.modules.pay.service.AliPayService;
import com.sqx.modules.sign.dao.GoldRecordsDao;
import com.sqx.modules.sign.entity.GoldRecords;
import com.sqx.modules.task.dao.TbDailyTasksDao;
import com.sqx.modules.task.dao.TbUserTaskDao;
import com.sqx.modules.task.entity.TbDailyTasks;
import com.sqx.modules.task.entity.TbUserTask;
import com.sqx.modules.tbOrders.dao.TbOrdersDao;
import com.sqx.modules.tbOrders.entity.TbOrders;
import com.sqx.modules.tbOrders.service.TbOrdersService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.locks.ReentrantReadWriteLock;

import static com.sqx.modules.utils.wx.WxPayUtils.getGeneralOrder;

/**
 * 支付宝支付处理--暂不做同步处理、回调方式使用异步
 */
@Slf4j
@RestController
@Api(value = "支付宝支付", tags = {"支付宝支付"})
@RequestMapping("/app/aliPay")
public class AliPayController {
    @Autowired
    private AliPayService aliPayService;
    @Autowired
    private CommonInfoService commonInfoService;
    @Autowired
    private PayDetailsDao payDetailsDao;

    @Autowired
    private UserService userService;
    @Autowired
    private UserMoneyDetailsService userMoneyDetailsService;

    @Autowired
    private UserMoneyDao userMoneyDao;

    @Autowired
    private TbOrdersDao tbOrdersDao;
    @Autowired
    private TbOrdersService orderService;

    @Autowired
    private TbDailyTasksDao tbDailyTasksDao;

    @Autowired
    private TbUserTaskDao tbUserTaskDao;

    @Autowired
    private GoldRecordsDao goldRecordsDao;

    @Login
    @ApiOperation("充值金额")
    @RequestMapping(value = "/payMoney", method = RequestMethod.POST)
    @Transactional(rollbackFor = Exception.class)
    public Result payAppMoney(@ApiParam("用户id")@RequestAttribute("userId") Long userId,
                              @ApiParam("金额") BigDecimal money,
                              @ApiParam("支付方式 4支付宝APP支付 5支付宝H5支付") Integer classify) {
        return aliPayService.payMoney(userId, money, null, classify);
    }


    @Login
    @ApiOperation("支付订单")
    @RequestMapping(value = "/payOrder", method = RequestMethod.POST)
    @Transactional(rollbackFor = Exception.class)
    public Result payOrder(@ApiParam("用户id")@RequestAttribute("userId") Long userId,
                           @ApiParam("订单id")Long orderId,
                           @ApiParam("支付方式 4支付宝APP支付 5支付宝H5支付")Integer classify) {
        return aliPayService.payOrder(userId, orderId, classify);
    }


    @RequestMapping(value = "/notifyApp", method = RequestMethod.POST)
    @Transactional(rollbackFor = Exception.class)
    public void notifyApp(HttpServletRequest request, HttpServletResponse response) {
        //获取支付宝POST过来反馈信息
        Map<String, String> params = new HashMap<String, String>();
        Map requestParams = request.getParameterMap();
        for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用。
            //valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }
        try {
            log.info("回调成功！！！");
            boolean flag = false;
            String pay = commonInfoService.findOne(97).getValue();
            if("1".equals(pay)){
                flag = AlipaySignature.rsaCheckV1(params, commonInfoService.findOne(64).getValue(), AliPayConstants.CHARSET, "RSA2");
            }else{
                CommonInfo urls = commonInfoService.findOne(200);
                flag = AlipaySignature.rsaCertCheckV1(params,urls.getValue()+"/alipayCertPublicKey_RSA2.crt", AliPayConstants.CHARSET, "RSA2");
            }
            log.info(flag + "回调验证信息");
            if (flag) {
                String tradeStatus = params.get("trade_status");
                if ("TRADE_SUCCESS".equals(tradeStatus) || "TRADE_FINISHED".equals(tradeStatus)) {
                    //支付宝返回的订单编号
                    String outTradeNo = params.get("out_trade_no");
                    log.error(outTradeNo);
                    //支付宝支付单号
                    String tradeNo = params.get("trade_no");
//                    String taskId = params.get("taskId");
                    orderService.payBack(outTradeNo);
                    TbOrders tbOrders = tbOrdersDao.selectOne(new QueryWrapper<TbOrders>().eq("order_number", outTradeNo));
                    if (tbOrders != null && tbOrders.getTaskId() != null) {
                        TbUserTask task = new TbUserTask();
                            task.setUserId(tbOrders.getBuyerId());
                            task.setTaskId(tbOrders.getTaskId());
                            task.setState(1);
                            task.setRewardClaimed(0);
                            task.setCreateTime(new Date());
                            tbUserTaskDao.insert(task);
                    }
//                        LocalDate startTime = LocalDate.now();
//                        int count = tbUserTaskDao.selectCount(new QueryWrapper<>(tbUserTaskDao.selectByCreateTime(tbOrders.getBuyerId(),
//                                startTime, Long.valueOf(taskId))));
//                        if (count > 0) {
//                            log.warn("该用户今天已经完成过该任务");
//                        } else {
//                            TbUserTask task = new TbUserTask();
//                            task.setUserId(tbOrders.getBuyerId());
//                            task.setTaskId(tbOrders.getTaskId());
//                            task.setState(1);
//                            task.setCreateTime(new Date());
//                            tbUserTaskDao.insert(task);
//                            GoldRecords records = new GoldRecords();
//                            records.setUserId(tbOrders.getBuyerId());
//                            records.setGoldChange(1);
//                            records.setRemark("买到物品奖励");
//                            records.setCreateTime(new Date());
//                            records.setRelatedId(tbOrders.getOrderId());
//                            TbDailyTasks tbDailyTasks = tbDailyTasksDao.selectById(tbOrders.getTaskId());
//                            records.setGoldCoins(tbDailyTasks.getSpecies());
//                            int resultCode = goldRecordsDao.insert(records);
//                            if (resultCode <= 0) {
//                                log.warn("买入物品失败");
//                            }
//                            UserEntity userEntity = userService.selectUserById(tbOrders.getBuyerId());
//                            userEntity.setTotalGold(userEntity.getTotalGold() + tbDailyTasks.getSpecies());
//                            userService.updateById(userEntity);
//                        }
//                    }
                    PayDetails payDetails = payDetailsDao.selectByOrderId(outTradeNo);
                    if (payDetails != null && payDetails.getState() == 0) {
                        payDetails.setState(1);
                        payDetails.setPayTime(DateUtils.format(new Date()));
                        payDetails.setTradeNo(tradeNo);
                        payDetailsDao.updateById(payDetails);
//                        payDetailsDao.updateState(payDetails.getId(), 1, DateUtils.format(new Date()), tradeNo);
                        if (payDetails.getType() == 1) {
                            //余额充值
                            userMoneyDao.updateMayMoney(1, payDetails.getUserId(), payDetails.getMoney());
                            UserMoneyDetails userMoneyDetails = new UserMoneyDetails();
                            userMoneyDetails.setMoney(BigDecimal.valueOf(payDetails.getMoney()));
                            userMoneyDetails.setUserId(payDetails.getUserId());
                            userMoneyDetails.setContent("支付宝充值：" + payDetails.getMoney());
                            userMoneyDetails.setTitle("账户充值");
                            userMoneyDetails.setType(1);
                            userMoneyDetails.setClassify(0);
                            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                            userMoneyDetails.setCreateTime(simpleDateFormat.format(new Date()));
                            userMoneyDetailsService.save(userMoneyDetails);
                        }else if (payDetails.getType() == 2) {
                            //支付订单
                            UserMoneyDetails userMoneyDetails = new UserMoneyDetails();
                            userMoneyDetails.setMoney(BigDecimal.valueOf(payDetails.getMoney()));
                            userMoneyDetails.setUserId(payDetails.getUserId());
                            userMoneyDetails.setContent("支付订单金额：" + payDetails.getMoney());
                            userMoneyDetails.setTitle("订单支付");
                            userMoneyDetails.setType(2);
                            userMoneyDetails.setClassify(1);
                            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                            userMoneyDetails.setCreateTime(simpleDateFormat.format(new Date()));
                            userMoneyDetailsService.save(userMoneyDetails);
                        }
                    }
                    writeResponse(response, "success");
                }
            }
        } catch (AlipayApiException e) {
            e.printStackTrace();
            log.info("回调验证失败！！！");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    private void writeResponse(HttpServletResponse response, String content) throws IOException {
        response.setCharacterEncoding("UTF-8");
        response.getWriter().write(content);
        response.getWriter().flush();
        response.getWriter().close();
    }
}
